﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using FrontDisplay.NativeMethods;
using Def.Log;

namespace FrontDisplay
{
    internal static class InterceptMouse
    {
        private static readonly LowLevelMouseProc Proc = HookCallback;
        private static IntPtr _hookId = IntPtr.Zero;

        public static void SetMouseHook()
        {
            if (_hookId == IntPtr.Zero)
            {
                _hookId = SetHook(Proc);
            }
        }

        public static void RemoveMouseHook()
        {
            if (_hookId != IntPtr.Zero)
            {
                UnhookWindowsHookEx(_hookId);
            }
            _hookId = IntPtr.Zero;
        }

        private static IntPtr SetHook(LowLevelMouseProc proc)
        {
            using (Process curProcess = Process.GetCurrentProcess())
            using (ProcessModule curModule = curProcess.MainModule)
            {
                return SetWindowsHookEx(WH_MOUSE_LL, proc,
                    GetModuleHandle(curModule.ModuleName), 0);
            }
        }

        private delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam);

        private static int _x;
        private static int _y;

        private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode >= 0)// && MouseMessages.WM_LBUTTONDOWN == (MouseMessages)wParam)
            {
                MSLLHOOKSTRUCT hookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));

                if (hookStruct.flags > 0)
                {
                    Logger.Info(string.Format("Message from iMON {0}x{1} {2} {3} {4} {5}", hookStruct.pt.x, hookStruct.pt.y, hookStruct.mouseData, hookStruct.flags, hookStruct.dwExtraInfo, wParam));

                    if (WinApi.MouseMessages.WM_MOUSEMOVE == (int)wParam)
                    {
                        _x = hookStruct.pt.x - (1680 + 1360); //TODO
                        _y = hookStruct.pt.y - (1050 - 600); //TODO
                    }

                    //TODO:
                    //if ((wParam == (IntPtr)WinApi.MouseMessages.WM_LBUTTONDOWN) || (wParam == (IntPtr)WinApi.MouseMessages.WM_LBUTTONUP))
                    {
                        WindowInteropHelper hWnd = new WindowInteropHelper(Application.Current.MainWindow);

                        //Logger.Info(string.Format("Message to MainWindow {0}x{1} {2}", _x, _y, (MouseMessages)wParam));
                        if ((wParam == (IntPtr)WinApi.MouseMessages.WM_LBUTTONDOWN) || (wParam == (IntPtr)WinApi.MouseMessages.WM_LBUTTONUP))
                        {
                            IntPtr lParamClickLocation = WinApi.MakeLParam(_x, _y);

                            WinApi.PostMessage(hWnd.Handle, WinApi.WM_USER + 100, wParam, lParamClickLocation);
                        }
                    }

                    //if (MouseMessages.WM_LBUTTONDOWN == (MouseMessages)wParam)
                    //{
                    //    if ((_x > 1680) && (_x < 1680 + 1360) && (_y > 1050 - 768) && (_y < 1050))
                    //    {
                    //        double x = (_x - 1680.0) / 1360.0;
                    //        double y = (_y - (1050.0 - 768.0)) / 768.0;

                    //        Logger.Info(string.Format("Message inside 2nd screen {0}x{1} {2}", x, y, (MouseMessages)wParam));
                    //        Global.MouseDown(x, y);
                    //    }
                    //}
                    return (IntPtr)1;
                }
            }
            return CallNextHookEx(_hookId, nCode, wParam, lParam);
        }

        private const int WH_MOUSE_LL = 14;

        [StructLayout(LayoutKind.Sequential)]
        private struct POINT
        {
            public int x;
            public int y;
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct MSLLHOOKSTRUCT
        {
            public POINT pt;
            public uint mouseData;
            public uint flags;
            public uint time;
            public IntPtr dwExtraInfo;
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook,
            LowLevelMouseProc lpfn, IntPtr hMod, uint dwThreadId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool UnhookWindowsHookEx(IntPtr hhk);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string lpModuleName);
    }
}